package com.stellar.circle.utils;

import java.util.concurrent.Callable;

/**
 * 重试工具类
 */
public class RetryUtils {

    public static <T> T retry(Callable<T> task, int maxAttempts, long delayMs, String operationName) {
        int attempt = 0;
        while (attempt < maxAttempts) {
            attempt++;
            try {
                return task.call();
            } catch (Exception e) {
                if (attempt >= maxAttempts) {
                    throw new OperationFailedException(operationName + " failed after " + maxAttempts + " attempts", e);
                }
                try {
                    Thread.sleep(delayMs);
                } catch (InterruptedException ie) {
                    Thread.currentThread().interrupt();
                    throw new OperationInterruptedException(operationName + " interrupted", ie);
                }
            }
        }
        throw new IllegalStateException("Unreachable code");
    }

    // 自定义异常
    public static class OperationFailedException extends RuntimeException {
        public OperationFailedException(String message, Throwable cause) {
            super(message, cause);
        }
    }

    public static class OperationInterruptedException extends RuntimeException {
        public OperationInterruptedException(String message, Throwable cause) {
            super(message, cause);
        }
    }
}